package com.yuwenxin.servlet.controller.music;

import com.yuwenxin.bean.Music;
import com.yuwenxin.bean.User;
import com.yuwenxin.core.PathSetting;
import com.yuwenxin.service.MusicService;
import com.yuwenxin.service.impl.MusicServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;


public class UploadMusicController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filePath = PathSetting.MUSIC_FILE_PATH;
        String photoPath = PathSetting.MUSIC_PHOTO_PATH;
        String projectPath = getServletContext().getRealPath("/");
        MusicService service = new MusicServiceImpl();
        Music music = new Music();

        User user = (User) req.getSession().getAttribute("user");
        System.out.println(user);
        System.out.println(user.getId());
        System.out.println(user.getPassword());
        music.setPosterId(user.getId());
        /**
         * 这里每上传一首歌，调用一次insert语句
         * 争取实现批量上传，文件夹上传
         * Music 需要的几个insert属性：name，filepath，photopath。
         * PostDate基于系统时间来确定
          */

        try {
            resp.setContentType("text/html;charset=utf-8");
            // 创建工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 创建缓存目录
            File file = new File(projectPath + "static/temp");
            factory.setRepository(file);
            // 创建ServletFileUpload对象，用于处理request中的文件内容
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            fileUpload.setHeaderEncoding("utf-8");
            // 通过ServletFileUpload中的parseRequest方法来解析请求中的文件信息，将文件内容封装在一个list中
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            PrintWriter writer = resp.getWriter();

            // 开始对获取的文件内容进行处理（遍历形式）
            for (FileItem fileItem :
                    fileItems) {
                if (fileItem.isFormField()){ // 这个方法判断内容是否为文本表单字段
                    String musicName = fileItem.getFieldName();
                    if (musicName.equals("musicName")){
                        if (!fileItem.getString().equals("")){
                            String value = fileItem.getString("utf-8");
                            writer.print("音乐名称：" + value + "<br/>");
                            music.setMusicName(value);
                        }
                    }
                }else {  // 这个代码块用于处理！fileItem.isFormField()的情况，即文件域
                    // 以下代码为核心

                    String fileName = fileItem.getName();  // 获取上传的文件名
                    String fieldName = fileItem.getFieldName();
                    if (fileName != null && !"".equals(fileName)) {
                        writer.print("上传的文件名称为：" + fileName + "<br/>");
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);  //截取文件名
                        fileName = UUID.randomUUID().toString() + "_" + fileName;  // 文件名唯一
                        File file_;
                        // 接下来根据后缀名不同，将不同的文件上传至不同的文件夹中，其他文件放至缓存文件夹中
                        /**
                         * TODO: 对于不同的文件后缀需要进行一系列的筛选工作，防止用户上传一些危害性文件或垃圾文件
                         * todo：将资源文件放至WEB-INF文件夹下，防止用户恶意访问
                         */
                        if (fieldName.equals("musicfile")){
                            file_ = new File(filePath + fileName);
                            music.setFilePath(filePath + fileName);
                        }else if (fieldName.equals("musicphoto")){
                            file_ = new File(photoPath + fileName);
                            music.setMusicPhotoPath(photoPath + fileName);
                        }else {
                            file_ = file;
                        }

                        // 使用输入输出流的形式来进行文件的传输
                        InputStream in = fileItem.getInputStream();
                        FileOutputStream out = new FileOutputStream(file_);
                        byte[] buffer = new byte[1024 * 1024];  // 每次读取1k字节内容
                        int len;
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                            fileItem.delete();

                        }
                        writer.print("上传文件成功！<br/>");
                        in.close();
                        out.close();
                    }
                }
            }
            service.musicUpload(music);
            }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
